<template>
  <div class="login-container" :style="{ backgroundImage: `url(${loginBg})` }">
    <div id="particles-js"></div>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">

      <div class="title-container">
        <div>
          <img src="@/assets/logo.png" class="logo">
        </div>
        <h3 class="title">Fs Japan Login</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <i class="el-icon-user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="Username"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <i class="el-icon-lock" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="Password"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <i :class="passwordType === 'password' ? 'el-icon-view' : 'el-icon-hide'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-form-item class="remember-me">
        <el-checkbox v-model="loginForm.remember" @change="handleRememberChange">
          <span class="remember-text">Remember me</span>
        </el-checkbox>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">
        {{ autoLoginAttempted ? 'Login' : (loginForm.remember && hasStoredCredentials ? 'Auto Login' : 'Login') }}
      </el-button>

      <!-- 如果有保存的凭据，显示提示信息 -->
      <div v-if="hasStoredCredentials && !autoLoginAttempted" class="login-tips">
        <el-alert
          title="Login information has been saved, click the button to log in quickly"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;">
        </el-alert>
      </div>
    </el-form>

    <el-dialog title="Or connect with" :visible.sync="showDialog">
      Can not be simulated on local, so please combine you own business simulation! ! !
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog>
    <div class="footer">
      Copyright © 2025 FS Japan Inc. All Rights Reserved.
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { encrypt, decrypt } from '@/utils/crypto'
import SocialSign from './components/SocialSignin'
import loginBg from '@/assets/login_images/bg.png'

export default {
  name: 'Login',
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      loginBg,
      hasStoredCredentials: false,
      autoLoginAttempted: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.loadStoredCredentials()
  },
  mounted() {
    this.initParticles()
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    /**
     * 加载保存的凭据
     */
    loadStoredCredentials() {
      try {
        const rememberedUsername = localStorage.getItem('fs_remembered_username')
        const rememberedPassword = localStorage.getItem('fs_remembered_password')
        const rememberState = localStorage.getItem('fs_remember_state')
        
        if (rememberedUsername && rememberedPassword && rememberState === 'true') {
          // 解密密码
          const decryptedPassword = decrypt(rememberedPassword)
          
          if (decryptedPassword) {
            this.loginForm.username = rememberedUsername
            this.loginForm.password = decryptedPassword
            this.loginForm.remember = true
            this.hasStoredCredentials = true
            
            // 显示提示信息
            this.$nextTick(() => {
              this.$message({
                message: 'Autofill saved logins',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      } catch (error) {
        console.error('加载保存的凭据失败:', error)
        this.clearStoredCredentials()
      }
    },

    /**
     * 清除保存的凭据
     */
    clearStoredCredentials() {
      localStorage.removeItem('fs_remembered_username')
      localStorage.removeItem('fs_remembered_password')
      localStorage.removeItem('fs_remember_state')
      this.hasStoredCredentials = false
    },

    /**
     * 处理Remember me状态变化
     */
    handleRememberChange(value) {
      if (!value) {
        // 如果取消勾选，清除保存的凭据
        this.clearStoredCredentials()
        this.$message({
          message: 'Saved logins cleared',
          type: 'info',
          duration: 2000
        })
      }
    },

    /**
     * 保存凭据到本地存储
     */
    saveCredentials() {
      try {
        if (this.loginForm.remember) {
          // 加密密码
          const encryptedPassword = encrypt(this.loginForm.password)
          
          localStorage.setItem('fs_remembered_username', this.loginForm.username)
          localStorage.setItem('fs_remembered_password', encryptedPassword)
          localStorage.setItem('fs_remember_state', 'true')
          
          this.$message({
            message: '登录信息已安全保存',
            type: 'success',
            duration: 2000
          })
        } else {
          this.clearStoredCredentials()
        }
      } catch (error) {
        console.error('保存凭据失败:', error)
        this.$message.error('保存登录信息失败')
      }
    },

    initParticles() {
      if (window.particlesJS) {
        window.particlesJS('particles-js', {
          particles: {
            number: {
              value: 80,
              density: {
                enable: true,
                value_area: 800
              }
            },
            color: {
              value: '#ffffff'
            },
            shape: {
              type: 'circle'
            },
            opacity: {
              value: 0.5,
              random: false
            },
            size: {
              value: 3,
              random: true
            },
            line_linked: {
              enable: true,
              distance: 150,
              color: '#ffffff',
              opacity: 0.4,
              width: 1
            },
            move: {
              enable: true,
              speed: 2,
              direction: 'none',
              random: false,
              straight: false,
              out_mode: 'out',
              bounce: false
            }
          },
          interactivity: {
            detect_on: 'canvas',
            events: {
              onhover: {
                enable: true,
                mode: 'grab'
              },
              onclick: {
                enable: true,
                mode: 'push'
              },
              resize: true
            }
          },
          retina_detect: true
        })
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.autoLoginAttempted = true
          
          this.$store.dispatch('user/login', this.loginForm)
            .then(async () => {
              // 登录成功后保存凭据
              this.saveCredentials()
              
              // 登录成功后立即获取用户头像
              try {
                await this.$store.dispatch('user/getAvatar')
              } catch (error) {
                console.warn('获取用户头像失败:', error)
                // 头像获取失败不影响登录流程，继续跳转
              }
              
              this.$router.push({ path: this.redirect || '/dashboard' })
            })
            .catch((error) => {
              this.loading = false
              console.error('登录失败:', error)
              
              // 如果是使用保存的凭据登录失败，清除保存的凭据
              if (this.hasStoredCredentials) {
                this.clearStoredCredentials()
                this.loginForm.password = ''
                this.$message.error('保存的登录信息已过期，请重新输入密码')
              }
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss">

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #333;
      height: 47px;
      caret-color: #333;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px rgba(255, 255, 255, 0.8) inset !important;
        -webkit-text-fill-color: #333 !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(0, 0, 0, 0.1);
    background: rgba(255, 255, 255, 0.8);
    border-radius: 5px;
    color: #333;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#333;

.login-container {
  min-height: 100%;
  width: 100%;
  background: no-repeat center center;
  background-size: cover;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  #particles-js {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 35px;
    margin: 0 auto;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 2;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    }
  }

  .el-input {
    input {
      transition: all 0.3s ease;
      
      &:focus {
        transform: translateY(-2px);
      }
    }
  }

  .el-button {
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
    }
  }

  .tips {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    text-align: center;
    margin-bottom: 40px;

    .logo {
      width: 120px;
      height: auto;
      margin-bottom: 20px;
    }

    .title {
      font-size: 26px;
      color: #333;
      margin: 0;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }

  .footer {
    position: absolute;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    color: #666;
    font-size: 14px;
  }

  .remember-me {
    margin-bottom: 20px;
    border: none !important;
    background: transparent !important;
    
    .el-checkbox {
      color: #666;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateX(5px);
      }
      
      .remember-text {
        font-size: 14px;
        font-weight: 500;
      }
      
      .el-checkbox__input.is-checked .el-checkbox__inner {
        background-color: #409EFF;
        border-color: #409EFF;
      }
      
      .el-checkbox__inner:hover {
        border-color: #409EFF;
      }
    }
  }

  .login-tips {
    margin-bottom: 20px;
    
    .el-alert {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
      border: 1px solid rgba(64, 158, 255, 0.2);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
      }
      
      .el-alert__icon {
        color: #409EFF;
      }
      
      .el-alert__title {
        color: #333;
        font-weight: 500;
      }
    }
  }
}
</style>
